package core;

import fileoperation.FileDeletion;
import gitobject.GitObject;
import gitobject.Index;
import repository.Repository;


import java.io.File;
import java.util.Iterator;
import java.util.Map;


public class JitRm {
    public static void remove(File file) throws Exception {
        File indexFile = new File(Repository.getGitDir()  + File.separator + "index");
        Index index;

        if (indexFile.exists()) {
            index = Index.deserialize(indexFile);
            String time = Index.getTime(file);
            Iterator iterator = index.fileOb.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object key = entry.getKey();
                GitObject value = (GitObject)entry.getValue();
                String t = (String)key;
                if(t.equals(time)){
                    index.fileOb.remove(key);
                    File toDel = new File(Repository.getGitDir() + File.separator + "objects" + File.separator
                            + value.getKey().substring(0, 2));
                    FileDeletion.deleteFile(indexFile);
                    FileDeletion.deleteFile(toDel);
                    index.writeObject();
                    return;
                }
            }
        } else {
            System.out.println("file doesn't exist!");
        }
    }

}
